//
//  RegisterViewController.m
//  SoutheastAsia
//
//  Created by rimi on 16/1/12.
//  Copyright © 2016年 zlj. All rights reserved.
//

#import "RegisterViewController.h"
#import "AVOSCloud/AVOSCLoud.h"

#define TEXT_HEIGHT 40
#define TEXT_WIDTH 220
#define TAG_BUTTON 100
#define BUTTON_LOCATION CGRectGetWidth(self.view.frame) / 2

@interface RegisterViewController () <UITextFieldDelegate>

@property (nonatomic, strong) UITextField *userNameField;
@property (nonatomic, strong) UITextField *passwordField;
@property (nonatomic, strong) UITextField *surePasswordField;
@property (nonatomic, strong) NSArray *arrayOfTextName;
@property (nonatomic, strong) UIImageView *backgroundImageView;
@property (nonatomic, strong) UIImageView *logoImageView;

//返回按钮
@property (nonatomic, strong) UIButton *backLoginButton;

- (void)initializeAppearance;

@end

@implementation RegisterViewController

#pragma mark - lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeAppearance];
}
#pragma mark -- private methods
- (void)initializeAppearance {
    [self.view addSubview:self.backgroundImageView];
    [self.view addSubview:self.passwordField];
    [self.view addSubview:self.userNameField];
    [self.view addSubview:self.surePasswordField];
    [self.view addSubview:self.backLoginButton];
    [self.view addSubview:self.logoImageView];
    
    //添加注册和重置按钮
    NSArray *buttonName = @[@"registerGo.png",@"registerCancel.png"];
    for (NSInteger index = 0; index < 2; index ++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = TAG_BUTTON + index;
        button.backgroundColor = [UIColor clearColor];
        [button setImage:[UIImage imageNamed:buttonName[index]] forState:UIControlStateNormal];
        button.bounds = CGRectMake(0, 0, BUTTON_LOCATION / 2, BUTTON_LOCATION / 8 + 10.0);
        if (index == 0) {
            button.center = CGPointMake(CGRectGetMidX(self.view.frame) - BUTTON_LOCATION / 2, CGRectGetMaxY(self.view.frame) - BUTTON_LOCATION / 4);
        } else {
            button.center = CGPointMake(CGRectGetMidX(self.view.frame) + BUTTON_LOCATION / 2, CGRectGetMaxY(self.view.frame) - BUTTON_LOCATION / 4);
        }
        [button addTarget:self action:@selector(controlOfRegister:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
    }
}
#pragma mark -- system protocol


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    int offset = frame.origin.y + 32 - (self.view.frame.size.height - 300);//键盘高度300
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    if(offset > 0)
        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
    
    [UIView commitAnimations];
}

//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
}
#pragma mark -- callback / action
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)controlOfRegister:(UIButton *)sender {
    switch (sender.tag - TAG_BUTTON) {
        case 0:
        {
            NSRange range = [self.userNameField.text rangeOfString:@" "];
            if (!(range.location == NSNotFound && range.length == 0)) {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"注册失败" message:@"账号不能含有空格" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
                return;
            }
            
            if (![self.passwordField.text isEqualToString:self.surePasswordField.text]) {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"注册失败" message:@"两次密码不相同" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
                return;
            }
            if (self.userNameField.text.length < 6 || self.userNameField.text.length > 16) {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"注册失败" message:@"用户名需要在6位到16位之间" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
                return;
            }
            if (self.passwordField.text.length < 8 || self.passwordField.text.length > 16) {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"注册失败" message:@"密码需要在8位到16位之间" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
                return;
            }
            AVUser *user = [AVUser user];
            user.username = _userNameField.text;
            user.password = _passwordField.text;
            [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"注册成功" message:@"" preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        [self dismissViewControllerAnimated:YES completion:nil];
                    }];
                    [alertController addAction:cancelAction];
                    [self presentViewController:alertController animated:YES completion:^{
                        self.userNameField.text = @"";
                        self.passwordField.text = @"";
                        self.surePasswordField.text = @"";
                    }];
                } else {
                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"注册失败" message:error.localizedDescription preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                    [alertController addAction:cancelAction];
                    [self presentViewController:alertController animated:YES completion:nil];
                }
            }];
            
        }
            break;
        case 1:
        {
            self.userNameField.text = @"";
            self.passwordField.text = @"";
            self.surePasswordField.text = @"";
        }
            break;
        default:
            break;
    }
}
//返回点击事件
- (void)backLoginButtonTaped:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark -- getter

- (NSArray *)arrayOfTextName {
    if (!_arrayOfTextName) {
        _arrayOfTextName = @[@"请输入注册名",@"请输入密码",@"请确认密码"];
    }
    return _arrayOfTextName;
}
//用户名输入框
- (UITextField *)userNameField {
    if (!_userNameField) {
        _userNameField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, TEXT_WIDTH , TEXT_HEIGHT)];
        _userNameField.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMidY(self.view.frame) + 60);
        _userNameField.borderStyle = UITextBorderStyleRoundedRect;
        _userNameField.placeholder = self.arrayOfTextName[0];
        _userNameField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _userNameField.delegate = self;
    }
    return _userNameField;
}
//密码输入框
- (UITextField *)passwordField {
    if (!_passwordField) {
        _passwordField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, TEXT_WIDTH , TEXT_HEIGHT)];
        _passwordField.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMidY(self.view.frame) + 120);
        _passwordField.borderStyle = UITextBorderStyleRoundedRect;
        _passwordField.placeholder = self.arrayOfTextName[1];
        _passwordField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _passwordField.secureTextEntry = YES;
        _passwordField.delegate = self;
    }
    return _passwordField;
}
//确认密码
- (UITextField *)surePasswordField {
    if (!_surePasswordField) {
        _surePasswordField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, TEXT_WIDTH , TEXT_HEIGHT)];
        _surePasswordField.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMidY(self.view.frame) + 180);
        _surePasswordField.borderStyle = UITextBorderStyleRoundedRect;
        _surePasswordField.placeholder = self.arrayOfTextName[2];
        _surePasswordField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _surePasswordField.secureTextEntry = YES;
        _surePasswordField.delegate = self;
    }
    return _surePasswordField;
}

//返回按钮
- (UIButton *)backLoginButton {
    if (!_backLoginButton) {
        _backLoginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _backLoginButton.frame = CGRectMake(5, 40, 40, 40);
        [_backLoginButton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
        [_backLoginButton addTarget:self action:@selector(backLoginButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backLoginButton;
}
//背景
- (UIImageView *)backgroundImageView {
    if (!_backgroundImageView) {
        _backgroundImageView = ({
            UIImageView *view = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"registerBackgroundImage.png"]];
            view.frame = CGRectMake(0, 0, CGRectGetMaxX(self.view.frame), CGRectGetMaxY(self.view.frame));
            view;
        });
    }
    return _backgroundImageView;
}
//logo
- (UIImageView *)logoImageView {
    if (!_logoImageView) {
        _logoImageView = ({
            UIImageView *view = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"title.png"]];
            view.bounds = CGRectMake(0, 0, CGRectGetMaxX(self.view.bounds), 400);
            view.center = self.view.center;
            
            view;
        });
    }
    return _logoImageView;
}
@end
